﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace Facebook.Api
{
    [FacebookObject("error_response")]
    public class FacebookApiException : Exception, IFacebookObject
    {
        public FacebookApiException(XElement content)
        {
            this.Init(content);
        }

        public FacebookApiException(IDictionary<String, Object> dict)
        {
            this.InnerDictionary = new Dictionary<String, Object>(dict);
        }

        public FacebookApiException()
        {
            this.InnerDictionary = new Dictionary<String, Object>();
        }

        public void Init(XElement content)
        {
            this.Content = new XDocument(content);
            this.InnerDictionary = new Dictionary<String, Object>();
        }

        public static Boolean IsApiException(XElement content)
        {
            return content.Name.LocalName == "error_response";
        }

        public XDocument Content { get; private set; }
        public IDictionary<String, Object> InnerDictionary { get; private set; }

        public Int16 ErrorCode
        {
            get { return this.GetValueType<Int16>("error_code"); }
            set { this.InnerDictionary["error_code"] = value; }
        }

        public String ErrorMsg
        {
            get { return this.GetString("error_msg"); }
            set { this.InnerDictionary["error_msg"] = value; }
        }

        public List<Arg> RequestArgs
        {
            get { return this.GetFacebookObjectCollection<Arg>("request_args"); }
            set { this.InnerDictionary["request_args"] = value; }
        }

        public override String Message { get { return this.ErrorMsg; } }

        public override IDictionary Data
        {
            get { return this.RequestArgs.ToDictionary(arg => arg.Key, arg => arg.Value); }
        }
    }
}